﻿namespace SolidMvvm {
	using System;
	using System.Collections.ObjectModel;
	using System.Collections.Specialized;
	using System.ComponentModel;

	public sealed class ObservableCollectionEx<T> : ObservableCollection<T> where T : INotifyPropertyChanged {
		public ObservableCollectionEx() {
			CollectionChanged += ObservableCollectionEx_CollectionChanged;
		}

		void ObservableCollectionEx_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
			if (e.NewItems != null)
				foreach (var newItem in e.NewItems) {
					var notifierItem = newItem as INotifyPropertyChanged;
					if (notifierItem == null)
						throw new InvalidOperationException("Unexpected item type in a collection.");

					notifierItem.PropertyChanged += notifierItem_PropertyChanged;
				}

			if (e.OldItems != null)
				foreach (var oldItem in e.OldItems) {
					var notifierItem = oldItem as INotifyPropertyChanged;
					if (notifierItem == null)
						throw new InvalidOperationException("Unexpected item type in a collection.");

					notifierItem.PropertyChanged -= notifierItem_PropertyChanged;
				}
		}

		void notifierItem_PropertyChanged(object sender, PropertyChangedEventArgs e) {
			if (ItemChanged != null)
				ItemChanged(this, IndexOf((T)sender));
		}

		public event EventHandler<int /* index */> ItemChanged;
	}
}
